package com.ls.blog.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ls.blog.dto.Recodes;
import com.ls.blog.entity.Tag;
import com.ls.blog.service.TagService;
import com.ls.blog.utils.R;
import com.ls.blog.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lishun
 * @since 2022-01-14
 */
@RestController
@RequestMapping("/tag")
@Api(tags = "标签模块")
public class TagController {

    @Autowired
    TagService tagService;


    @PostMapping("/saveTag")
    public Result saveTag(@RequestBody Tag tag){
        if (StringUtils.isEmpty(tag.getName())){
            R.fail("标签名称不能为空！");
        }
        QueryWrapper<Tag> queryWrapper = new QueryWrapper<Tag>();
        queryWrapper.eq("name", tag.getName());
        List<Tag> tagList = tagService.list(queryWrapper);
        if (tagList.size() > 0){
           R.fail("添加失败，已有该标签名称");
        }
        Boolean result = tagService.save(tag);
        if (result){
            return R.ok("添加标签成功！");
        }else {
            return R.fail("添加标签失败！");
        }

    }

    /**
     * 查询所有标签
     * @return
     */
    @GetMapping("/list")
    public Result<List<Tag>> getAllTag(){
        return R.ok(tagService.list());
    }

    /**
     * 标签的分页查询
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/getTagByPage")
    @ApiOperation("标签的分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current",value = "当前页") ,
            @ApiImplicitParam(name = "size",value = "每页的数量"),
    })
    public Result<Recodes<Tag>> getTagByPage(Long current, Long size){
        return R.ok(tagService.pageTags(current, size));
    }

    /**
     * 通过名称查找标签
     * @param name
     * @return
     */
    @GetMapping("/getTagByName")
    public Result<List<Tag>> getTagByName(String name){
        return R.ok(tagService.getTagByName(name));
    }

    /**
     * 更新标签
     * @param tag
     * @return
     */
    @PutMapping("/updateTag")
    public Result updateTag(@RequestBody Tag tag){
        if (StringUtils.isEmpty(tag.getName())){
            return R.fail("分类名称不能为空");
        }
        tagService.updateTag(tag);
        return R.ok("修改成功");
    }

    /**
     * 删除标签
     * @param id
     * @return
     */
    @DeleteMapping("deleteTagById")
    public Result deleteTagById(Long id){
        tagService.deleteTagById(id);
        return R.ok();
    }

    /**
     * 根据id查询标签
     * @param id
     * @return
     */
    @GetMapping("/getTagById")
    public Result<Tag> getTagById(Long id){
        return R.ok(tagService.getTagById(id));
    }

}
